import glob
import os
import tkinter as tk 
from tkinter import messagebox
from PIL import Image, ImageTk, ImageDraw
import keyboard 
import math

def find_png_files(directory):
    png_files = glob.glob(os.path.join(directory, '**', '*.png'), recursive=True)
    return png_files
def create_window(parent=None):
    # 创建窗口
    if parent is None:
        root = tk.Tk()
    else:
        root = tk.Toplevel(parent)
    #root = tk.Tk()
    root.title("序列帧修改器")
    root.config(bg="grey")
    root.geometry("1800x1000")

    # background_image = Image.open("D:/Users/admin/Downloads/composite/body_output/50001_ATTACK_0/0.png")
    # background_photo = ImageTk.PhotoImage(background_image)
    # canvas.
    # 暂停修改--将index保持不动，一直重复刷同一帧

    global offX, offY
    offX = 60
    offY = 50
    tk.Label(root,text="请输入文件夹路径",bg='green').place(x=offX,y=2)
    tk.Label(root,text="勾选复选框启用锚点修改功能",bg='green').place(x=offX,y=20)

    check_var = tk.IntVar()
    check_var1 = tk.IntVar()
    check_var2 = tk.IntVar()
    check_var3 = tk.IntVar()
    def check_status():
        if check_var.get():
            return 'on'
        else:
            return 'off'

    def check_status1():
        if check_var1.get():
            return 'on'
        else:
            return 'off'

    def check_status2():
        if check_var2.get():
            return 'on'
        else:
            return 'off'

    #输入框一
    entry_var = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var)
    check_anchor = tk.Checkbutton(root,variable=check_var).place(x=offX + 150,y=offY - 3)
    entry_path.place(x=offX,y=offY)

    tk.Label(root,text="请输入模型ID或模型ID具体动作",bg='green').place(x=offX,y=offY + 85)
    entry_role = tk.StringVar()
    entry_rolename = tk.Entry(root, textvariable=entry_role)
    entry_rolename.place(x=offX, y= offY + 113)
    #输入框二
    entry_var1 = tk.StringVar()
    entry_path1 = tk.Entry(root, textvariable=entry_var1)
    check_anchor1 = tk.Checkbutton(root,variable=check_var1).place(x=offX + 350,y=offY - 3)
    entry_path1.place(x=offX+200,y=offY)

    tk.Label(root,text="请输入技能ID",bg='green').place(x=offX +200,y=offY + 85)
    entry_skill = tk.StringVar()
    entry_skillname = tk.Entry(root, textvariable=entry_skill)
    entry_skillname.place(x=offX + 200, y= offY + 113)
    #输入框三
    entry_var2 = tk.StringVar()
    entry_path2 = tk.Entry(root, textvariable=entry_var2)
    check_anchor2 = tk.Checkbutton(root,variable=check_var2).place(x=offX + 550,y=offY - 3)
    entry_path2.place(x=offX+400,y=offY)

    tk.Label(root,text="请输入武器ID或武器ID具体动作",bg='green').place(x=offX +400,y=offY + 85)
    entry_wuqi = tk.StringVar()
    entry_wuqiname = tk.Entry(root, textvariable=entry_wuqi)
    entry_wuqiname.place(x=offX +400, y= offY + 113)

    #切换指定ID角色
    def change_role():
        global role_button, role_name, directory_type,cur_frame_index
        role_name = entry_role.get()
        directory_type = []
        #index = 0
        for item in all_directory_type:
            for name in item:
                if role_name in name:
                    directory_type.append(name)
                    #cur_directory_type_index = index
                    #return
            #index+=1
        load_images_from_directory1()
        cur_frame_index = 0
    #切换指定ID技能
    def change_skill():
        global skill_button, skill_name,directory_type1,cur_frame_index
        skill_name = entry_skill.get()
        directory_type1 = []
        #index = 0
        for item in all_directory_type1:
            for name in item:
                if skill_name in name:
                    #cur_directory_type_index1 = index
                    directory_type1.append(name)
                    #return
            #index+=1
        load_images_from_directory2()
        cur_frame_index = 0
    #切换指定ID武器
    def change_wuqi():
        global wuqi_button, wuqi_name, directory_type2,cur_frame_index
        wuqi_name = entry_wuqi.get()
        directory_type2 = []
        #index = 0
        for item in all_directory_type2:
            for name in item:
                if wuqi_name in name:
                    #cur_directory_type_index2 = index
                    directory_type2.append(name)
                    #return
            #index+=1
        load_images_from_directory3()
        cur_frame_index = 0

    role_button = tk.Button(root, text="加载指定ID模型", command= change_role,bg='skyblue').place(x=offX, y= offY + 140)
    skill_button = tk.Button(root, text="加载指定ID技能", command= change_skill,bg='red').place(x=offX + 200, y= offY + 140)
    wuqi_name= tk.Button(root, text="加载指定ID武器", command= change_wuqi,bg='orange').place(x=offX + 400, y= offY + 140)

    global image_frames,image_frames1, image_frames2, image_frames3, cur_frame_index, cur_directory_type_index,input_x, input_y,input_x_value , input_y_value,monster_image
    input_x = 0
    input_y = 0
    input_x_value = 0
    input_y_value = 0
    image_frames = []
    image_frames1 = []
    image_frames2 = []
    image_frames3 = []
    cur_directory_type_index = 0
    cur_frame_index = 0
    coordinates=[(0,-30),(60,-30),(60,0),(60,30),(0,30),(-60,30),(-60,0),(-60,-30)]
    monster_image=[]
    # 从目录加载图片
    def load_images_from_directory():
        global image_frames,image_frames1, image_frames2,image_frames3,cur_frame_index, cur_directory_type_index
        image_paths = []
        for i, d in enumerate(all_directory_type[cur_directory_type_index]):
            image_paths.extend(find_png_files(image_frames_path + "/" + d))

        if not image_paths:
            messagebox.showerror("Error", "目录一没有图片文件")

        if image_frames_path1 != '':
            image_paths1 = []
            for i, d in enumerate(all_directory_type1[cur_directory_type_index1]):
                image_paths1.extend(find_png_files(image_frames_path1 + "/" + d))
            image_frames1 = [Image.open(path) for path in image_paths1]

        if image_frames_path2 != '':
            image_paths2 = []
            for i, d in enumerate(all_directory_type2[cur_directory_type_index2]):
                image_paths2.extend(find_png_files(image_frames_path2 + "/" + d))
            image_frames2 = [Image.open(path) for path in image_paths2]

        cur_frame_index = 0
        image_frames = [Image.open(path) for path in image_paths]
        reset_window()

        # 从目录加载指定动作图片
    def load_images_from_directory1():
        global image_frames,cur_frame_index, cur_directory_type_index, directory_type
        image_paths = []
        for i, d in enumerate(directory_type):
            image_paths.extend(find_png_files(image_frames_path + "/" + d))
        if not image_paths:
            messagebox.showerror("Error", "目录一没有图片文件")
        cur_frame_index = 0
        image_frames = [Image.open(path) for path in image_paths]
        reset_window()

    def load_images_from_directory2():
        global image_frames1,cur_frame_index,directory_type1
        if image_frames_path1 != '' :
            image_paths1 = []
            for i, d in enumerate(directory_type1):
                image_paths1.extend(find_png_files(image_frames_path1 + "/" + d))
            image_frames1 = [Image.open(path) for path in image_paths1]
            cur_frame_index = 0
            reset_window()

    def load_images_from_directory3():
        global image_frames2,cur_frame_index,directory_type2
        if image_frames_path2 != '':
            image_paths2 = []
            for i, d in enumerate(directory_type2):
                image_paths2.extend(find_png_files(image_frames_path2 + "/" + d))
            image_frames2 = [Image.open(path) for path in image_paths2]
            cur_frame_index = 0
            reset_window()


    # 获取输入路径
    def get_input_path():
        global image_frames, last_button, next_button, image_frames_path, image_frames_path1,image_frames_output_path, image_frames_output_path1
        global all_directory_type,all_directory_type1, cur_directory_type_index,cur_directory_type_index1
        #路径一
        all_directory_type = []
        cur_directory_type_index = 0
        image_frames_path = entry_var.get().replace("\\", "/")
        if image_frames_path != '':
            image_frames_output_path = image_frames_path + "_output"
            all_directory = [d for d in os.listdir(image_frames_path) if os.path.isdir(os.path.join(image_frames_path, d))]
            dir_name = ""
            for i, d in enumerate(all_directory):
                net_dir_name = os.path.basename(d)
                if dir_name.split("_")[0] == net_dir_name.split("_")[0]:
                    all_directory_type[-1].append(net_dir_name)
                else:
                    dir_name = net_dir_name
                    all_directory_type.append([dir_name])

        if not all_directory_type:
            messagebox.showerror("Error", "路径一没有目录")
            #return
        #路径二
        all_directory_type1 = []
        cur_directory_type_index1 = 0
        image_frames_path1 = entry_var1.get().replace("\\", "/")
        if image_frames_path1 != '':
            image_frames_output_path1 = image_frames_path1 + "_output"
            all_directory1 = [d for d in os.listdir(image_frames_path1) if os.path.isdir(os.path.join(image_frames_path1, d))]
            dir_name1 = ""
            for i, d in enumerate(all_directory1):
                net_dir_name1 = os.path.basename(d)
                if dir_name1.split("_")[0] == net_dir_name1.split("_")[0]:
                    all_directory_type1[-1].append(net_dir_name1)
                else:
                    dir_name1 = net_dir_name1
                    all_directory_type1.append([dir_name1])

        #路径三
        global all_directory_type2,cur_directory_type_index2,image_frames_path2,image_frames_output_path2
        all_directory_type2 = []
        cur_directory_type_index2 = 0
        image_frames_path2 = entry_var2.get().replace("\\", "/")
        if image_frames_path2 != '':
            image_frames_output_path2 = image_frames_path2 + "_output"
            all_directory2 = [d for d in os.listdir(image_frames_path2) if os.path.isdir(os.path.join(image_frames_path2, d))]
            dir_name2 = ""
            for i, d in enumerate(all_directory2):
                net_dir_name2 = os.path.basename(d)
                if dir_name2.split("_")[0] == net_dir_name2.split("_")[0]:
                    all_directory_type2[-1].append(net_dir_name2)
                else:
                    dir_name2 = net_dir_name2
                    all_directory_type2.append([dir_name2])


        load_images_from_directory()


    get_input_button = tk.Button(root, text="加载图片", command=get_input_path,bg='skyblue')
    get_input_button.place(x=offX+200,y=offY - 40)


    #按钮，上下切换图片资源一
    def btn_last_directory():
        global cur_directory_type_index,cur_directory_type_index1
        if cur_directory_type_index <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index -= 1
        load_images_from_directory()

    def btn_next_directory():
        global cur_directory_type_index
        if cur_directory_type_index >= len(all_directory_type)-1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index += 1
        load_images_from_directory()

    last_button = tk.Button(root, text="上一个", command=btn_last_directory)
    last_button.place(x=offX + 10,y=offY+40)
    next_button = tk.Button(root, text="下一个", command=btn_next_directory)
    next_button.place(x=offX+90,y=offY+40)

    #按钮，上下切换图片资源二
    global last_button1,next_button1
    def btn_last_directory1():
        global cur_directory_type_index1
        if cur_directory_type_index1 <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index1 -= 1
        load_images_from_directory()

    def btn_next_directory1():
        global cur_directory_type_index1
        if cur_directory_type_index1 >= len(all_directory_type1)-1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index1 += 1
        load_images_from_directory()

    last_button1 = tk.Button(root, text="上一个", command=btn_last_directory1)
    last_button1.place(x=offX +210,y=offY+40)
    next_button1 = tk.Button(root, text="下一个", command=btn_next_directory1)
    next_button1.place(x=offX+290,y=offY+40)

    #按钮，上下切换图片资源三
    global last_button2,next_button2
    def btn_last_directory2():
        global cur_directory_type_index2
        if cur_directory_type_index2 <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index2 -= 1
        load_images_from_directory()

    def btn_next_directory2():
        global cur_directory_type_index2
        if cur_directory_type_index2 >= len(all_directory_type2)-1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index2 += 1
        load_images_from_directory()

    last_button1 = tk.Button(root, text="上一个", command=btn_last_directory2)
    last_button1.place(x=offX +410,y=offY+40)
    next_button1 = tk.Button(root, text="下一个", command=btn_next_directory2)
    next_button1.place(x=offX+490,y=offY+40)


    #图像绘制位置坐标
    canvas = tk.Canvas(root, width=800, height=800, bg="gray")
    canvas.place(x=offX+70,y=offY+180)

    # 重置窗口
    def reset_window():
        global image_max_width, image_max_height, canvas_width, canvas_height, center_x, center_y, cur_frame_index
        image_max_width = 0
        image_max_height = 0
        canvas_width = 750
        canvas_height = 800
        center_x = 0
        center_y = 0
        cur_frame_index = 0
        for i, img in enumerate(image_frames):
            image_max_width = max(image_max_width, img.width)
            image_max_height = max(image_max_height, img.height)

        root_width = max(canvas_width, image_max_width)
        root_height = max(canvas_height, image_max_height)
        #处理大图
        root.geometry(f"{root_width}x{root_height}")
        canvans_width = max(512,image_max_width)
        canvans_height = max(512,image_max_height)
        canvas.config(width=800, height=800)
        center_x = canvas_width / 2
        center_y = canvas_height / 2

    # 鼠标左键点击
    def on_image_click_down():
        global speed , root_after,input_x, input_y
        if check_status() == 'on':
            # root_after = root.after(speed, update_frame)
            # offset_x = int(event.x - center_x)
            # offset_y = int(event.y - center_y)

            offset_x =  int(input_x)
            offset_y =  int(input_y)

            new_image_width = image_max_width + abs(offset_x*2)
            new_image_height = image_max_height + abs(offset_y*2)
            for i, img in enumerate(image_frames):
                new_image_path = img.filename.replace("\\", "/")
                new_image = Image.new("RGBA", (new_image_width, new_image_height))
                start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                # crop_box = new_image.getbbox() # 剪切图片有效区域
                # if crop_box:
                #     crop_x = min(crop_box[0], new_image.width - crop_box[2])
                #     crop_y = min(crop_box[1], new_image.height - crop_box[3])
                #     new_image = new_image.crop((crop_x, crop_y, new_image.width - crop_x, new_image.height - crop_y))

                if not new_image_path.startswith(image_frames_output_path):
                    new_image_path = new_image_path.replace(image_frames_path, image_frames_output_path)
                if not os.path.exists(os.path.dirname(new_image_path)):
                    os.makedirs(os.path.dirname(new_image_path))
                new_image.save(new_image_path)
                image_frames[i] = Image.open(new_image_path)

            reset_window()

        if check_status1() == 'on':
            # root_after = root.after(speed, update_frame)
            offset_x =  int(input_x)
            offset_y =  int(input_y)
            new_image_width = image_max_width + abs(offset_x*2)
            new_image_height = image_max_height + abs(offset_y*2)
            for i, img in enumerate(image_frames1):
                new_image_path1 = img.filename.replace("\\", "/")
                new_image = Image.new("RGBA", (new_image_width, new_image_height))
                start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                # crop_box = new_image.getbbox() # 剪切图片有效区域
                # if crop_box:
                #     crop_x = min(crop_box[0], new_image.width - crop_box[2])
                #     crop_y = min(crop_box[1], new_image.height - crop_box[3])
                #     new_image = new_image.crop((crop_x, crop_y, new_image.width - crop_x, new_image.height - crop_y))

                if not new_image_path1.startswith(image_frames_output_path1):
                    new_image_path1 = new_image_path1.replace(image_frames_path1, image_frames_output_path1)
                if not os.path.exists(os.path.dirname(new_image_path1)):
                    os.makedirs(os.path.dirname(new_image_path1))
                new_image.save(new_image_path1)
                image_frames1[i] = Image.open(new_image_path1)

        if check_status2() == 'on':
            # root_after = root.after(speed, update_frame)
            offset_x =  int(input_x)
            offset_y =  int(input_y)
            new_image_width = image_max_width + abs(offset_x*2)
            new_image_height = image_max_height + abs(offset_y*2)
            for i, img in enumerate(image_frames2):
                new_image_path2 = img.filename.replace("\\", "/")
                new_image = Image.new("RGBA", (new_image_width, new_image_height))
                start_x = int(new_image_width / 2 - img.width / 2 + offset_x)
                start_y = int(new_image_height / 2 - img.height / 2 + offset_y)
                new_image.paste(img, (start_x, start_y, start_x + img.width, start_y + img.height))

                # crop_box = new_image.getbbox() # 剪切图片有效区域
                # if crop_box:
                #     crop_x = min(crop_box[0], new_image.width - crop_box[2])
                #     crop_y = min(crop_box[1], new_image.height - crop_box[3])
                #     new_image = new_image.crop((crop_x, crop_y, new_image.width - crop_x, new_image.height - crop_y))

                if not new_image_path2.startswith(image_frames_output_path2):
                    new_image_path2 = new_image_path2.replace(image_frames_path2, image_frames_output_path2)
                if not os.path.exists(os.path.dirname(new_image_path2)):
                    os.makedirs(os.path.dirname(new_image_path2))
                new_image.save(new_image_path2)
                image_frames2[i] = Image.open(new_image_path2)

        input_x = 0
        input_y = 0

    # 鼠标指针样式
    def on_canvas_enter(event):
        event.widget.config(cursor="tcross")
    def on_canvas_leave(event):
        event.widget.config(cursor="")
    # canvas.bind("<Button-1>", on_image_click_down)
    canvas.bind("<Enter>", on_canvas_enter)
    canvas.bind("<Leave>", on_canvas_leave)

    global speed, root_after
    speed = 100

    #暂停,继续，重置，调速方法
    entry_speed = tk.StringVar()
    entry_speedvalue = tk.Entry(root,textvariable=entry_speed,width= 7)
    entry_speedvalue.place(x=offX,y=offY + 350)
    def set_speed_play():
        global stop_button, continue_button, first_frame_button, speed_button,speed
        speed = entry_speed.get()

    global isplay
    isplay = True
    def stop_play():
        global root_after
        global speed,isplay
        if(isplay):
            root.after_cancel(root_after)
        else:
            root_after = root.after(speed, update_frame)
        isplay = not isplay

    def continue_play():
        global root_after
        global speed
        root_after = root.after(speed, update_frame)

    def restart_play():
        global cur_frame_index
        cur_frame_index = 0

    stop_button = tk.Button(root, text="暂停/继续", command= stop_play).place(x=offX,y=offY + 200)
    stop_button = tk.Button(root, text="继续播放", command= continue_play).place(x=offX,y=offY + 250)
    stop_button = tk.Button(root, text="从头播放", command= restart_play).place(x=offX,y=offY + 300)
    stop_button = tk.Button(root, text="调整速度", command= set_speed_play).place(x=offX,y=offY + 380)


    # 刷新帧
    def update_frame():
        global photo_image, photo_image1,photo_image2,photo_image3,cur_frame_index, root_after,path_index1,image_name
        global input_x, input_y
        if image_frames:
            #目录一
            if  cur_frame_index >= len(image_frames):
                path_index = len(image_frames) - 1
                image_frame = image_frames[path_index]
                photo_image = ImageTk.PhotoImage(image_frame)
            else:
                image_frame = image_frames[cur_frame_index]
                photo_image = ImageTk.PhotoImage(image_frame)
            #目录二
            if image_frames_path1 != '':
                if cur_frame_index >= len(image_frames1):
                    path_index1 = len(image_frames1)-1
                    image_frame1 = image_frames1[path_index1]
                    photo_image1 = ImageTk.PhotoImage(image_frame1)
                else:
                    image_frame1 = image_frames1[cur_frame_index]
                    photo_image1 = ImageTk.PhotoImage(image_frame1)
            #目录三
            if image_frames_path2 != '':
                if cur_frame_index >= len(image_frames2):
                    path_index2 = len(image_frames2)-1
                    image_frame2 = image_frames2[path_index2]
                    photo_image2 = ImageTk.PhotoImage(image_frame2)
                else:
                    image_frame2 = image_frames2[cur_frame_index]
                    photo_image2 = ImageTk.PhotoImage(image_frame2)

            canvas.delete("all")  # 清除之前的图像
            canvas.create_rectangle(center_x-image_frame.width/2, center_y-image_frame.height/2, center_x+image_frame.width/2, center_y+image_frame.height/2, fill="white", outline="black")
            if monster_image:
                canvas.create_image(monster_x, monster_y, anchor=tk.CENTER, image=monster_image[0])
            if check_status() == 'on':
                canvas.create_image(center_x + int(input_x), center_y + int(input_y), anchor=tk.CENTER, image=photo_image)
            else:
                canvas.create_image(center_x , center_y, anchor=tk.CENTER, image=photo_image)
            if image_frames_path1 != '':
                if check_status1() == 'on':
                    canvas.create_image(center_x+ int(input_x), center_y + int(input_y), anchor=tk.CENTER, image=photo_image1)
                else:
                    canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image1)
            if image_frames_path2 != '':
                if check_status2() == 'on':
                    canvas.create_image(center_x+ int(input_x), center_y + int(input_y), anchor=tk.CENTER, image=photo_image2)
                else :
                    canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image2)

            canvas.create_line(0, center_y , canvas_width, center_y, fill="red", width=1)
            canvas.create_line(center_x, 0, center_x, canvas_height, fill="red", width=1)

            #显示当前正在播放的人物，技能和武器动画名称
            image_name = image_frame.filename.replace("\\", "/").replace(image_frames_path, "")
            root.title("人物" + image_name)
            length = len(image_frames)
            if image_frames_path1 != '':
                image_name1 = image_frame1.filename.replace("\\", "/").replace(image_frames_path1, "")
                root.title("人物" + image_name + "   技能" + image_name1)
                length = max(len(image_frames),len(image_frames1))
            if image_frames_path2 != '':
                image_name2 = image_frame2.filename.replace("\\", "/").replace(image_frames_path2, "")
                root.title("人物" + image_name + "   技能" + image_name1 + "   武器" + image_name2)
                length = max(len(image_frames),len(image_frames1),len(image_frames2))

            cur_frame_index = (cur_frame_index + 1) % length  # 循环显示

        root_after = root.after(speed, update_frame)  # 每100毫秒更新一次

    def save_canvas_as_image():
        global image_frames, image_frames1,image_name, change_hierarchys
        ind = 0
        image_frame = image_frames[0]
        length = len(image_frames) - 1

        # length2 = len(image_frames1) - 1
        # lists = []
        # if(length > length2):
        #     lists = image_frames
        # else :
        #     lists = image_frames1

        for i, img in enumerate(image_frames1):
            # 拿到主图
            if( i > length):
                image_frame = image_frames[length]
            else:
                image_frame = image_frames[i]

            # if( i > length2):
            #     image_frame2 = image_frames1[length2]
            # else:
            #     image_frame2 = image_frames1[i]
            # 获取两张图片的尺寸
            width1, height1 = image_frame.size
            width2, height2 = img.size

            # 找到最大的宽度和高度
            max_width = max(width1, width2)
            max_height = max(height1, height2)

            # 创建一个与较大图片尺寸相同的透明背景
            new_img1 = Image.new("RGBA", (max_width, max_height), (255, 255, 255, 0))
            new_img2 = Image.new("RGBA", (max_width, max_height), (255, 255, 255, 0))

            # 将原图粘贴到新创建的透明背景上，保持居中
            new_img1.paste(image_frame, ((max_width - width1) // 2, (max_height - height1) // 2))
            new_img2.paste(img, ((max_width - width2) // 2, (max_height - height2) // 2))

            # 叠加两张图片，保留透明部分
            if(change_hierarchys):
                final_image = Image.alpha_composite(new_img1, new_img2)
            else:
                final_image = Image.alpha_composite(new_img2, new_img1)

            # 保存为文件
            file_name = image_name.split("/")[1]
            Path = image_frames_output_path + "/" + file_name + "/" +str(ind) + ".png"
            if not os.path.exists(os.path.dirname(Path)):
                os.makedirs(os.path.dirname(Path))
            final_image.save(Path)
            ind +=1

    # 保存Canvas内容为图片
    save_button = tk.Button(root, text="合并图像", command=save_canvas_as_image).place(x=offX,y=offY + 460)

    change_hierarchys = True
    tk.Label(root,text="路径一置底",bg='green').place(x=offX,y=offY + 570)

    def change_hierarchy():
        global change_hierarchys, hierarchy_button
        change_hierarchys = not change_hierarchys
        if(change_hierarchys):
            tk.Label(root,text="路径一置底",bg='green').place(x=offX,y=offY + 570)
        else:
            tk.Label(root,text="路径二置底",bg='orange').place(x=offX,y=offY + 570)

    hierarchy_button = tk.Button(root, text= "层级切换", command=change_hierarchy).place(x=offX,y=560)

    def on_key_event(event):
        global input_x, input_y, input_x_value , input_y_value
        if keyboard.is_pressed('up'):  # 检查是否按下了 '' 键
            input_y -= int(input_y_value)
        if keyboard.is_pressed('down'):
            input_y += int(input_y_value)
        if keyboard.is_pressed('left'):
            input_x -= int(input_x_value)
        if keyboard.is_pressed('right'):
            input_x += int(input_x_value)
            # input_x += input_x
            # print("检测到 right 键！::" + str(input_x))
            # print(f"Key {event.name} was pressed")

    # 注册一个键盘事件
    keyboard.on_press(on_key_event)

    save_change_img_local = tk.Button(root, text= "裁剪图片",command= on_image_click_down,bg="skyblue").place(x=offX + 450,y=offY - 40)

    #调整量输入框
    entry_var_change = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var_change,width=5)
    entry_path.place(x=offX + 300,y=offY - 37)

    def save_change_input_values():
        global input_x_value, input_y_value
        input_x_value = entry_var_change.get()
        input_y_value = entry_var_change.get()

    save_change_input_value = tk.Button(root, text= "调整",command= save_change_input_values,bg="skyblue").place(x=offX + 350,y=offY - 40)

    # ---------------------------------------------------------------------------------------------------------------------------------------------
    global imgs_scale,scale_value, scale_index
    scale_value = 1
    imgs_scale = []
    scale_index = 0

    #缩放图片路径输入框
    entry_scale_change_path = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_scale_change_path)
    entry_path.place(x=offX + 950,y=offY - 40)

    #图像绘制位置坐标
    canvas_scale = tk.Canvas(root, width=800, height=800, bg="gray")
    canvas_scale.place(x=offX+950,y=offY+180)


    # 缩放图像
    def resize_images():
        global button_scale_load,button_scale_sure,scale_value,input_folder,output_folder,imgs_scale_path
        global iModel
        imgs_scale_path = []
        input_folder = entry_scale_change_path.get()
        output_folder = input_folder + "\\scale_output"#r"D:\Users\admin\Desktop\File\130001\output"

        if not os.path.exists(output_folder):
            os.makedirs(output_folder)

        for filename in os.listdir(input_folder):
            if filename.endswith('.png') or filename.endswith('.jpg'):
                imgs_scale_path.append(os.path.join(input_folder, filename)) # = [Image.open(os.path.join(input_folder, filename))]
                img = Image.open(os.path.join(input_folder, filename))
                resize = [math.ceil(img.size[0]*scale_value), math.ceil(img.size[1]*scale_value)]
                if(iModel==1):
                  resized_img = img.resize(resize, Image.Resampling.NEAREST)
                elif(iModel==2):
                    resized_img = img.resize(resize, Image.Resampling.BOX)
                elif(iModel==3):
                    resized_img = img.resize(resize, Image.Resampling.BILINEAR)
                elif(iModel==4):
                    resized_img = img.resize(resize, Image.Resampling.HAMMING)
                elif(iModel==5):
                    resized_img = img.resize(resize, Image.Resampling.BICUBIC)
                elif(iModel==6):
                    resized_img = img.resize(resize, Image.Resampling.LANCZOS)
                resized_img.save(os.path.join(output_folder, filename))


    # 加载
    def load_images():
        global imgs_scale,button_scale
        global button_scale_load,button_scale_sure,scale_value,input_folder,output_folder,imgs_scale_path
        imgs_scale_path = []
        input_folder = entry_scale_change_path.get()
        # output_folder = input_folder + "\\output"#r"D:\Users\admin\Desktop\File\130001\output"

        # if not os.path.exists(output_folder):
        #     os.makedirs(output_folder)

        for filename in os.listdir(input_folder):
            if filename.endswith('.png') or filename.endswith('.jpg'):
                imgs_scale_path.append(os.path.join(input_folder, filename)) # = [Image.open(os.path.join(input_folder, filename))]

        imgs_scale = [Image.open(path) for path in imgs_scale_path]
        update_frame_sclae()


    #缩放量输入框
    entry_scale_change = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_scale_change,width=5)
    entry_path.place(x=offX + 950,y=offY - 3)

    def get_scale_value():
        global scale_value
        scale_value = 0
        scale_value = float(entry_scale_change.get())
        # update_frame_sclae()

    def SetImagaModel1():
        global iModel
        iModel = 1
    def SetImagaModel2():
        global iModel
        iModel = 2
    def SetImagaModel3():
        global iModel
        iModel = 3
    def SetImagaModel4():
        global iModel
        iModel = 4
    def SetImagaModel5():
        global iModel
        iModel = 5
    def SetImagaModel6():
        global iModel
        iModel = 6

    button_scale_load = tk.Button(root, text="缩放图片",command=resize_images).place(x=offX + 1070,y=offY - 6)
    button_scale_load = tk.Button(root, text="最近邻插值",command=SetImagaModel1).place(x=offX + 1070 + 80,y=offY - 6)
    button_scale_load = tk.Button(root, text="方形插值",command=SetImagaModel2).place(x=offX + 1070 + 160,y=offY - 6)
    button_scale_load = tk.Button(root, text="双线性插值",command=SetImagaModel3).place(x=offX + 1070 + 240,y=offY - 6)
    button_scale_load = tk.Button(root, text="哈明插值",command=SetImagaModel4).place(x=offX + 1070 + 320,y=offY - 6)
    button_scale_load = tk.Button(root, text="双三次插值",command=SetImagaModel5).place(x=offX + 1070 + 400,y=offY - 6)
    button_scale_load = tk.Button(root, text="Lanczos 插值",command=SetImagaModel6).place(x=offX + 1070 + 480,y=offY - 6)
    button_scale_sure = tk.Button(root, text="预览",command=get_scale_value).place(x=offX + 990, y=offY - 6)
    button_scale = tk.Button(root, text="加载图片",command=load_images).place(x=offX + 1110,y=offY  - 40)

    def update_frame_sclae():
        global imgs_scale,scale_index,photo,resized_img,name,root_after2
        if imgs_scale:
            canvas_scale.delete("all")
            length = len(imgs_scale)
            img_scale = imgs_scale[scale_index]
            name = img_scale.filename.split("\\")[len(img_scale.filename.split("\\")) - 1]
            resize = [math.ceil(img_scale.size[0]*scale_value), math.ceil(img_scale.size[1]*scale_value)]
            resized_img = img_scale.resize(resize, Image.Resampling.LANCZOS)
            photo = ImageTk.PhotoImage(resized_img)
            x = int(photo.width() / 2)
            y = int(photo.height() / 2)

            canvas_scale.create_rectangle(x-photo.width()/2, y-photo.height()/2, x+photo.width()/2, y+photo.height()/2, fill="white", outline="black")
            canvas_scale.create_image(x,y, anchor=tk.CENTER, image=photo)

            canvas_scale.create_line(left_value,up_value,right_value,up_value,fill="red")
            canvas_scale.create_line(left_value,down_value,right_value,down_value,fill="red")
            canvas_scale.create_line(left_value,up_value,left_value,down_value,fill="red")
            canvas_scale.create_line(right_value,up_value,right_value,down_value,fill="red")

            scale_index = (scale_index + 1) % length  # 循环显示
        root_after2 =  root.after(200, update_frame_sclae)


    #-----------------------------------------------------------------------------------------------------------------------------------------------------------
    #裁剪图片边界区域
    global left_value,right_value,up_value,down_value
    left_value = 1
    right_value = 1
    up_value = 1
    down_value = 1


    def get_tailor_value():
        global button_tailor_left,button_tailor_right,button_tailor_up,button_tailor_down,imgs_scale
        global left_value,right_value,up_value,down_value,resized_img
        if(entry_tailor_left.get() != ""):
            left_value = int(entry_tailor_left.get())
        if(entry_tailor_right.get() != ""):
            right_value = resized_img.size[0] - int(entry_tailor_right.get())
        else:
            right_value = imgs_scale[0].width
        if(entry_tailor_up.get() != ""):
            up_value = int(entry_tailor_up.get())
        if(entry_tailor_down.get()!= ""):
            down_value = resized_img.size[1] - int(entry_tailor_down.get())
        else:
            down_value = imgs_scale[0].height
        # update_frame_sclae()



    #裁剪left输入框
    entry_tailor_left = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_tailor_left,width=5)
    entry_path.place(x=offX + 950,y=offY + 60)
    # button_tailor_left = tk.Button(root, text="确认",command=get_tailor_value).place(x=offX + 990, y=offY + 57)
    tk.Label(root,text="左边界",bg="green").place(x=offX + 950, y=offY + 30)

    #裁剪right输入框
    entry_tailor_right = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_tailor_right,width=5)
    entry_path.place(x=offX + 1030,y=offY + 60)
    # button_tailor_right = tk.Button(root, text="确认",command=get_tailor_value).place(x=offX + 1090, y=offY + 57)
    tk.Label(root,text="右边界",bg="green").place(x=offX + 1030, y=offY + 30)

    #裁剪up输入框
    entry_tailor_up = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_tailor_up,width=5)
    entry_path.place(x=offX + 1130,y=offY + 60)
    # button_tailor_up = tk.Button(root, text="确认",command=get_tailor_value).place(x=offX + 1190, y=offY + 57)
    tk.Label(root,text="上边界",bg="green").place(x=offX + 1130, y=offY + 30)

    #裁剪down输入框
    entry_tailor_down = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_tailor_down,width=5)
    entry_path.place(x=offX + 1230,y=offY + 60)
    button_tailor_down = tk.Button(root, text="预览",command=get_tailor_value).place(x=offX + 1290, y=offY + 57)
    tk.Label(root,text="下边界",bg="green").place(x=offX + 1230, y=offY + 30)

    #裁剪图片指定边界
    def tailor():
        global left_value,right_value,up_value,down_value,resized_img,imgs_scale,img

        finally_Names = input_folder.split("\\")
        finally_Name = finally_Names[len(finally_Names) - 1]
        output_folder = input_folder + "\\" + finally_Name#r"D:\Users\admin\Desktop\File\130001\output"
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)

        for img in imgs_scale:
            name = img.filename.split("\\")[len(img.filename.split("\\")) - 1]
            img_crop = img.crop((left_value,up_value,right_value,down_value))
            img_crop.save(os.path.join(output_folder, name))

    button_tailor = tk.Button(root, text="保存图片",command=tailor,bg="skyblue").place(x=offX + 1290, y=offY + 97)

    def monsterAdd():
        index=int(entry_var_monsterIndex.get())
        index+=1
        entry_var_monsterIndex.set(str(index))

    def monsterMinus():
        index = int(entry_var_monsterIndex.get())
        index -= 1
        entry_var_monsterIndex.set(str(index))

    def loadMonster():
        global monster_x,monster_y
        monsterPath = entry_var_monster.get()
        count=int(entry_var_plaid.get())
        index=int(entry_var_monsterIndex.get())
        if index<=0 or index>8 or monsterPath=='':
            return
        image = Image.open(monsterPath)
        monster_image.clear()
        monster_image.append(ImageTk.PhotoImage(image))
        # 计算 Canvas 的中心位置
        monster_x = center_x+coordinates[index-1][0]*count
        monster_y = center_y+coordinates[index-1][1]*count


    #怪物图片输入框
    entry_var_monster = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_var_monster,width=15)
    tk.Label(root,text="请输入怪物图片路径",bg='green').place(x=offX+720,y=12)
    entry_path.place(x=offX + 600,y=offY - 37)

    #怪物位置输入框
    entry_var_monsterIndex = tk.StringVar()
    entry_var_monsterIndex.set(1)
    entry_path = tk.Entry(root, textvariable=entry_var_monsterIndex,width=5)
    tk.Label(root,text="请输入怪物位置",bg='green').place(x=offX+720,y=offY)
    entry_path.place(x=offX + 630,y=offY)
    monsterAdd_button = tk.Button(root, text=" - ", command=monsterMinus)
    monsterAdd_button.place(x=offX + 600,y=offY)
    monsterMinus_button = tk.Button(root, text=" + ", command=monsterAdd)
    monsterMinus_button.place(x=offX+680,y=offY)

    #怪物图片加载
    loadMonster_button = tk.Button(root, text="怪物加载", command=loadMonster)
    loadMonster_button.place(x=offX + 622,y=offY+40)

    #格子数
    entry_var_plaid = tk.StringVar()
    entry_var_plaid.set(1)
    entry_path = tk.Entry(root, textvariable=entry_var_plaid,width=5)
    tk.Label(root,text="请输入格子数量",bg='green').place(x=offX+720,y=offY+80)
    entry_path.place(x=offX + 630,y=offY+80)

    #--------------------------------------------------------------------------------------------------------------------------------------------------
    # 灰度取值（去除黑色底色）
    def apply_alpha_from_grayscale():
        global imgs_scale,new_imgs_scale,button_clear_color,input_folder
        new_imgs_scale = []

        for img in imgs_scale:

            # 将图片转换为灰度图像
            grayscale_img = img.convert("L")

            # 将灰度图作为alpha通道
            r, g, b, _ = img.split()  # 分离原始图片的RGB通道
            new_img = Image.merge("RGBA", (r, g, b, grayscale_img))  # 将灰度图像作为Alpha通道
            # 返回处理好的图片
            # new_imgs_scale.append(new_img)
            name = img.filename.split("\\")[len(img.filename.split("\\")) - 1]
            new_img.save(os.path.join(input_folder, name))

    button_clear_color = tk.Button(root, text="去除黑底并保存",command=apply_alpha_from_grayscale,bg="skyblue").place(x=offX + 1290, y=offY + 130)

    update_frame()
    update_frame_sclae()
    root.mainloop()